rm(list = ls())

library(tidyverse)
library(fixest)

## Scaled covariates 

dat <- readRDS('data/balance_check_covars.rds')  

covars <- names(dat)[!names(dat) %in% c('freibad', 'indoor', 'any_pool', 'AGS')]

## Balance 

plot_df <- lapply(covars, function(var_name){
  
  form <- as.formula(paste('freibad ~ ', var_name))
  
  m1 <- feols(form, data = dat %>% filter(indoor == 0)) %>%
    broom::tidy(conf.int = T) %>%
    filter(term == var_name) %>%
    mutate(sample = 'Baseline: no pool') 
  
  m2 <- feols(form, data = dat %>% filter(any_pool == 1)) %>%
    broom::tidy(conf.int = T) %>%
    filter(term == var_name) %>%
    mutate(sample =  'Baseline: indoor pool')
  
  return(bind_rows(m1, m2))
  
}) %>%
  reduce(bind_rows)

## Labels for plotting 

plot_df <- plot_df %>%
  mutate(var_label = recode(term,
                            `age_below_18` = 'Age: under 18',
                            `age_above_64` = 'Age: above 65',
                            `share_vacant` = 'Share vacant apartments',
                            `hospital_any` = 'Hospital in muni.',
                            `gini` = 'Inequality (Gini)',
                            `outflow_pc` = 'Out-migration',
                            `inflow_pc`= 'Migration: inflows',
                            `p50` = 'Median income',
                            `mean_net_income_fdz` = 'Mean income',
                            `unemp` = 'Pop. share on social welfare',
                            `density` = 'Pop. density'
                            
                            
  )) %>%
  mutate(var_label = fct_rev(fct_reorder(var_label, var_label)))

## Plot This 

p1 <- ggplot(plot_df, aes(x = var_label, 
                          y = estimate, 
                          ymin = conf.low, 
                          ymax = conf.high,
                          col = sample,
                          shape = sample)) + 
  geom_errorbar(width = 0, position = position_dodge(.2)) + 
  geom_point(fill = 'white', 
             position = position_dodge(.2)) + 
  theme_classic() + 
  coord_flip() + 
  geom_hline(yintercept = 0, linetype = 'dotdash') + 
  labs(x = '',
       shape = '',
       col = '',
       title = '',
       y = 'Mean difference\n(in standard deviations)') + 
  theme(legend.position = 'bottom') + 
  scale_color_grey()

p1 




